class dfs_memory_search:
    def __init__(self, maze):

        self.judge = [[-1 for _ in range(1001)] for _ in range(1001)]
        self.maze = [[-1 for _ in range(1001)] for _ in range(1001)]
        self.m = len(maze)
        self.n = len(maze[0])
        for i in range(1,self.m + 1):
            for j in range(1, self.n + 1):
                self.maze[i][j] = maze[i - 1][j - 1]
        self.originalx = [[0 for _ in range(1001)] for _ in range(1001)]
        self.originaly = [[0 for _ in range(1001)] for _ in range(1001)]
        self.cur_x = 0
        self.cur_y = 0
        self.sum = 0

    def dfs(self, x, y):
        if x < 1 or y < 1 or x > self.m  or y > self.n:
            return
        if self.judge[x][y] != -1:
            return
        
        self.sum += 1
        directions = [[0,1], [0,-1], [1,0], [-1,0]]
        self.originalx[x][y] = self.cur_x
        self.originaly[x][y] = self.cur_y
        self.judge[x][y] = 0

        for i in directions:
            if self.maze[x + i[0]][y + i[1]] != self.maze[x][y]:
                self.dfs(x + i[0], y + i[1])

    def search(self, targets):
        for target in targets:
            self.sum = 0
            _x = target[0]
            _y = target[1]
            if self.judge[self.originalx[_x][_y]] \
                [self.originaly[_x][_y]] > 0:
                print(self.judge[self.originalx[_x][_y]]\
                    [self.originaly[_x][_y]])
                continue
            self.cur_x = _x
            self.cur_y = _y
            self.dfs(_x, _y)
            print(self.sum)
            self.judge[_x][_y] = self.sum
            self.originalx[_x][_y] = _x
            self.originaly[_x][_y] = _y

if __name__ == "__main__":
    targets = [[1,1],[1,2], [1,3],[2,1],\
         [2,2], [2,3], [3,1], [3,2], [3,3]]
    maze = [[0,1,1],[1,1,1], [1,1,1]]
    dfs_ms = dfs_memory_search(maze)
    dfs_ms.search(targets)




















